<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 200px;height: 200px;background: pink;border: 1px solid black;
            position: absolute;top: 0;left: 0;
            text-align: center;line-height: 200px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    var obox=document.querySelector(".box");
    document.onkeydown=function(eve){
        var e=eve||window.event;
        // 获取键码（有兼容）
        // 正常浏览器
        // console.log(e.keyCode);
        // ie 浏览器
        // console.log(e.which)
        var code=e.keyCode||e.which;

        if(code == 37){
            obox.innerHTML = "按下了←";
        }
        if(code == 38){
            obox.innerHTML = "按下了↑";
        }
        if(code == 39){
            obox.innerHTML = "按下了→";
        }
        if(code == 40){
            obox.innerHTML = "按下了↓";
        }

        // 键盘控制元素的位置
        switch(code){
            case 37:
                obox.style.left=obox.offsetLeft-100+"px";
                break;
            case 38:
                obox.style.top=obox.offsetTop-100+"px";
                break;
            case 39:
                obox.style.left=obox.offsetLeft+100+"px"
                break;
            case 40:
                obox.style.top=obox.offsetTop+100+"px"
                break;
        }
    }
</script>
</html>